import React, { useEffect } from 'react';
import loadjs from 'loadjs';

const loadMap = () => {
  if (!loadjs.isDefined('amap')) {
    window.aMapLoadPromise = new Promise((resolve) => {
      loadjs(
        'https://webapi.amap.com/maps?v=1.4.15&key=2a7f8edcf5b284647d8ae1006da64792',
        'amap',
        () => {
          resolve();
        },
      );
    });
  }
  return window.aMapLoadPromise;
};

/**
 * 高德地图
 */
export default (props) => {
  const {
    id = 'amap',
    center = [117.000923, 36.675807],
    zoom = 11,
    style,
    onLoaded,
    mapRef,
  } = props;

  useEffect(() => {
    loadMap().then(() => {
      const { AMap } = window;
      const map = new AMap.Map(id, { center, zoom });
      if (mapRef) {
        mapRef.current = map;
      }
      if (onLoaded) {
        onLoaded(map);
      }
    });
  }, []);

  return <div id={id} style={{ width: '100%', height: '100%', ...style }} />;
};
